package com.ruoyi.emergency.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.emergency.domain.EmTaskLog;
import com.ruoyi.emergency.service.IEmTaskLogService;
import com.ruoyi.emergency.service.IEmTaskService; // 1. 导入任务Service接口
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 应急任务处理日志Controller
 *
 * @author ruoyi
 * @date 2025-07-09
 */
@RestController
@RequestMapping("/emergency/log")
public class EmTaskLogController extends BaseController
{
    @Autowired
    private IEmTaskLogService emTaskLogService;

    @Autowired
    private IEmTaskService emTaskService; // 2. 注入任务Service

    /**
     * 查询应急任务处理日志列表
     */
    @GetMapping("/list")
    public TableDataInfo list(EmTaskLog emTaskLog)
    {
        startPage();
        List<EmTaskLog> list = emTaskLogService.selectEmTaskLogList(emTaskLog);
        return getDataTable(list);
    }

    /**
     * 导出应急任务处理日志列表
     */
    @PreAuthorize("@ss.hasPermi('emergency:log:export')")
    @Log(title = "应急任务处理日志", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EmTaskLog emTaskLog)
    {
        List<EmTaskLog> list = emTaskLogService.selectEmTaskLogList(emTaskLog);
        ExcelUtil<EmTaskLog> util = new ExcelUtil<EmTaskLog>(EmTaskLog.class);
        util.exportExcel(response, list, "应急任务处理日志数据");
    }

    /**
     * 获取应急任务处理日志详细信息
     */
    @PreAuthorize("@ss.hasPermi('emergency:log:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(emTaskLogService.selectEmTaskLogById(id));
    }

    /**
     * 新增应急任务处理日志
     */
    @PreAuthorize("@ss.hasPermi('emergency:log:add')")
    @Log(title = "应急任务处理日志", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EmTaskLog emTaskLog)
    {
        // 逾期校验
        if (emTaskLog.getTaskId() != null) {
            com.ruoyi.emergency.domain.EmTask task = emTaskService.selectEmTaskById(emTaskLog.getTaskId());
            if (task != null && task.getStatus() != null) {
                // 检查任务是否已完成
                if (task.getStatus() == 2) {
                    return AjaxResult.error("任务已完成，无法重复处理");
                }
                // 检查任务是否已逾期（包括数据库中已标记为逾期的和当前时间超过截止时间的）
                if (task.getStatus() == 3 || (task.getStatus() != 2 && task.getDeadline() != null && new Date().after(task.getDeadline()))) {
                    return AjaxResult.error("任务已逾期，无法处理");
                }
            }
        }
        emTaskLog.setHandleTime(new Date()); // 先赋值
        int result = emTaskLogService.insertEmTaskLog(emTaskLog);
        // 新增：同步更新任务表状态
        if (emTaskLog.getTaskId() != null && emTaskLog.getStatus() != null) {
            // 3. 转成Long类型，防止类型不匹配
            emTaskService.updateTaskStatus(emTaskLog.getTaskId(), emTaskLog.getStatus().longValue());
        }
        return toAjax(result);
    }

    /**
     * 修改应急任务处理日志
     */
    @PreAuthorize("@ss.hasPermi('emergency:log:edit')")
    @Log(title = "应急任务处理日志", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EmTaskLog emTaskLog)
    {
        return toAjax(emTaskLogService.updateEmTaskLog(emTaskLog));
    }

    /**
     * 删除应急任务处理日志
     */
    @PreAuthorize("@ss.hasPermi('emergency:log:remove')")
    @Log(title = "应急任务处理日志", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(emTaskLogService.deleteEmTaskLogByIds(ids));
    }
}